#!/bin/bash

# Enrigin GStreamer 插件一键部署脚本

set -e

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo ""
echo -e "${BLUE}=========================================="
echo "  Enrigin GStreamer 插件一键部署"
echo "==========================================${NC}"
echo ""

# 步骤 1: 检查依赖
echo -e "${YELLOW}[1/5] 检查依赖...${NC}"

# 检查 GStreamer
if ! command -v gst-launch-1.0 &> /dev/null; then
    echo -e "${RED}✗ GStreamer 未安装${NC}"
    echo "请安装: sudo apt-get install gstreamer1.0-tools libgstreamer1.0-dev"
    exit 1
fi
echo -e "${GREEN}✓ GStreamer 已安装${NC}"

# 检查 CMake
if ! command -v cmake &> /dev/null; then
    echo -e "${RED}✗ CMake 未安装${NC}"
    echo "请安装: sudo apt-get install cmake"
    exit 1
fi
echo -e "${GREEN}✓ CMake 已安装${NC}"

# 检查 Rivs SDK
if [ ! -f "/opt/rivs/lib/libvcenc.so" ]; then
    echo -e "${YELLOW}⚠ Rivs SDK 可能未安装${NC}"
fi

echo ""

# 步骤 2: 编译
echo -e "${YELLOW}[2/5] 编译插件...${NC}"
./scripts/build_all.sh
echo ""

# 步骤 3: 安装
echo -e "${YELLOW}[3/5] 安装插件...${NC}"
sudo ./scripts/install.sh
echo ""

# 步骤 4: 验证
echo -e "${YELLOW}[4/5] 验证安装...${NC}"

if gst-inspect-1.0 enrigindec > /dev/null 2>&1; then
    echo -e "${GREEN}✓ enrigindec 验证通过${NC}"
else
    echo -e "${RED}✗ enrigindec 验证失败${NC}"
    exit 1
fi

if gst-inspect-1.0 enriginenc > /dev/null 2>&1; then
    echo -e "${GREEN}✓ enriginenc 验证通过${NC}"
else
    echo -e "${RED}✗ enriginenc 验证失败${NC}"
    exit 1
fi

echo ""

# 步骤 5: 快速测试
echo -e "${YELLOW}[5/5] 运行快速测试...${NC}"
echo ""

echo "测试 1: 生成测试视频并编码..."
timeout 5 gst-launch-1.0 videotestsrc num-buffers=150 pattern=ball ! \
    video/x-raw,format=NV12,width=1280,height=720,framerate=30/1 ! \
    enriginenc codec=h264 bitrate=2000 gop=30 ! \
    h264parse ! mp4mux ! filesink location=/tmp/enrigin_test.mp4 \
    > /dev/null 2>&1 || true

if [ -f "/tmp/enrigin_test.mp4" ]; then
    size=$(stat -f%z "/tmp/enrigin_test.mp4" 2>/dev/null || stat -c%s "/tmp/enrigin_test.mp4")
    if [ "$size" -gt 10000 ]; then
        echo -e "${GREEN}✓ 编码测试通过 (生成 $size 字节)${NC}"
    else
        echo -e "${YELLOW}⚠ 编码测试文件过小${NC}"
    fi
else
    echo -e "${YELLOW}⚠ 编码测试未生成文件${NC}"
fi

echo ""
echo -e "${GREEN}=========================================="
echo "  部署完成！"
echo "==========================================${NC}"
echo ""
echo -e "${BLUE}插件信息:${NC}"
gst-inspect-1.0 enrigindec | grep -E "Plugin Details|Description" | head -4
echo ""
gst-inspect-1.0 enriginenc | grep -E "Plugin Details|Description" | head -4
echo ""

echo -e "${BLUE}快速开始:${NC}"
echo "  查看快速指南: cat QUICKSTART.md"
echo "  运行测试: cd tests && ./test_enriginenc.sh"
echo "  性能对比: cd tests && ./compare_decoder_cpu.sh"
echo ""

echo -e "${BLUE}文档位置:${NC}"
echo "  主文档: README.md"
echo "  快速开始: QUICKSTART.md"
echo "  详细文档: docs/"
echo ""

echo -e "${GREEN}✓ 所有步骤完成！${NC}"
echo ""
